// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//
#include <melon/benchmark.h>
#include <melon/init/init.h>
#include <pollux/expression/vector_function.h>
#include <pollux/functions/lib/benchmarks/FunctionBenchmarkBase.h>
#include <pollux/functions/prestosql/registration/registration_functions.h>
#include <pollux/type/tz/time_zone_map.h>
#include <pollux/vector/vector_fuzzer.h>

using namespace kumo::pollux;
using namespace kumo::pollux::test;

namespace {

class HourFunction : public exec::VectorFunction {
 public:
  const tz::TimeZone* MELON_NULLABLE
  getTimeZoneIfNeeded(const core::QueryConfig& config) const {
    const tz::TimeZone* timeZone = nullptr;
    if (config.adjustTimestampToTimezone()) {
      auto sessionTzName = config.sessionTimezone();
      if (!sessionTzName.empty()) {
        timeZone = tz::locateZone(sessionTzName);
      }
    }
    return timeZone;
  }

  void apply(
      const SelectivityVector& rows,
      std::vector<VectorPtr>& args,
      const TypePtr& /* outputType */,
      exec::EvalCtx& context,
      VectorPtr& result) const override {
    POLLUX_CHECK_EQ(args.size(), 1);
    const auto* timestamps =
        static_cast<const Timestamp*>(args[0]->values_as_void());

    // Initialize flat results vector.
    BaseVector::ensure_writable(rows, BIGINT(), context.pool(), result);
    auto rawResults = result->as<FlatVector<int64_t>>()->mutableRawValues();

    // Check if we need to adjust the current UTC timestamps to
    // the user provided session timezone.
    const auto* timeZone =
        getTimeZoneIfNeeded(context.execCtx()->queryCtx()->queryConfig());
    if (timeZone != nullptr) {
      rows.applyToSelected([&](int row) {
        auto timestamp = timestamps[row];
        timestamp.toTimezone(*timeZone);
        int64_t seconds = timestamp.getSeconds();
        std::tm dateTime;
        gmtime_r((const time_t*)&seconds, &dateTime);
        rawResults[row] = dateTime.tm_hour;
      });
    } else {
      rows.applyToSelected([&](int row) {
        int64_t seconds = timestamps[row].getSeconds();
        std::tm dateTime;
        gmtime_r((const time_t*)&seconds, &dateTime);
        rawResults[row] = dateTime.tm_hour;
      });
    }
  }

  static std::vector<std::shared_ptr<exec::FunctionSignature>> signatures() {
    // timestamp -> bigint
    return {exec::FunctionSignatureBuilder()
                .returnType("bigint")
                .argumentType("timestamp")
                .build()};
  }
};

class DateTimeBenchmark : public functions::test::FunctionBenchmarkBase {
 public:
  DateTimeBenchmark() : FunctionBenchmarkBase() {
    functions::prestosql::registerDateTimeFunctions();
    registerVectorFunction(
        "hour_vector",
        HourFunction::signatures(),
        std::make_unique<HourFunction>());
  }

  void run(const std::string& functionName) {
    melon::BenchmarkSuspender suspender;

    VectorFuzzer::Options opts;
    opts.vectorSize = 10'000;
    auto data = vectorMaker_.row_vector(
        {VectorFuzzer(opts, pool()).fuzzFlat(TIMESTAMP())});
    auto exprSet =
        compileExpression(fmt::format("{}(c0)", functionName), data->type());
    suspender.dismiss();

    doRun(exprSet, data);
  }

  void runDateTrunc(const std::string& unit) {
    melon::BenchmarkSuspender suspender;
    VectorFuzzer::Options opts;
    opts.vectorSize = 10'000;
    auto data = vectorMaker_.row_vector(
        {VectorFuzzer(opts, pool()).fuzzFlat(TIMESTAMP())});
    auto exprSet = compileExpression(
        fmt::format("date_trunc('{}', c0)", unit), data->type());
    suspender.dismiss();

    doRun(exprSet, data);
  }

  void doRun(exec::ExprSet& exprSet, const RowVectorPtr& row_vector) {
    int cnt = 0;
    for (auto i = 0; i < 100; i++) {
      cnt += evaluate(exprSet, row_vector)->size();
    }
    melon::doNotOptimizeAway(cnt);
  }
};

BENCHMARK(truncYear) {
  DateTimeBenchmark benchmark;
  benchmark.runDateTrunc("year");
}

BENCHMARK(truncMonth) {
  DateTimeBenchmark benchmark;
  benchmark.runDateTrunc("month");
}

BENCHMARK(truncDay) {
  DateTimeBenchmark benchmark;
  benchmark.runDateTrunc("day");
}

BENCHMARK(truncHour) {
  DateTimeBenchmark benchmark;
  benchmark.runDateTrunc("hour");
}

BENCHMARK(truncMinute) {
  DateTimeBenchmark benchmark;
  benchmark.runDateTrunc("minute");
}

BENCHMARK(truncSecond) {
  DateTimeBenchmark benchmark;
  benchmark.runDateTrunc("second");
}

BENCHMARK(year) {
  DateTimeBenchmark benchmark;
  benchmark.run("year");
}

BENCHMARK(month) {
  DateTimeBenchmark benchmark;
  benchmark.run("month");
}

BENCHMARK(day) {
  DateTimeBenchmark benchmark;
  benchmark.run("day");
}

BENCHMARK(hour) {
  DateTimeBenchmark benchmark;
  benchmark.run("hour");
}

BENCHMARK_RELATIVE(hour_vector) {
  DateTimeBenchmark benchmark;
  benchmark.run("hour_vector");
}

BENCHMARK(minute) {
  DateTimeBenchmark benchmark;
  benchmark.run("minute");
}

BENCHMARK(second) {
  DateTimeBenchmark benchmark;
  benchmark.run("second");
}
} // namespace

int main(int argc, char** argv) {
  melon::Init init{&argc, &argv};

  melon::runBenchmarks();
  return 0;
}
